package com.example.demo.config;

import com.example.demo.model.TokenUser;
import com.example.demo.tools.Constant;
import com.example.demo.tools.JWTUtils;
import com.example.demo.tools.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Mr.Xi
 * Date: 2023-04-24
 * Time: 20:31
 */
@Component
@Slf4j
public class JWTAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException,RuntimeException {
        // 获取 token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        // 解析 token
        Map<String, Object> map = null;
        try{
            map = JWTUtils.getData(token);
            if(Objects.isNull(map)){
                throw new RuntimeException("token 非法!");
            }
        }catch (Exception e){
            throw new RuntimeException("token 非法!");
        }
        // 通过 id 查询 redis
        String userId = Constant.USER_LOGIN + map.get(Constant.TOKEN_KEY);
        TokenUser loginUser = redisUtil.getCacheObject(userId);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录!");
        }
        // 将查询数据放到 SecurityContextHolder 中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
